package com.alan.libapi.api;

import android.text.TextUtils;

import com.alan.libapi.exception.NullParameterException;
import com.alan.libapi.model.persistent.HttpType;
import com.alan.libapi.model.persistent.Parameter;
import com.alan.library.allog.KLog;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

/**
 * @className: HttpEngine
 * @describtion: HttpEngine
 * @author: AlanWang
 * @email: 850267876@qq.com
 * @time: 2016/4/17 19:29
 */
public class HttpEngine {
	private final static String TAG = "HttpEngine";
	private final static String ENCODE_TYPE = "UTF-8";
	private final static int READ_TIMEOUT_GET = 5000;
	private final static int CONNECTION_TIMEOUT_GET = 5000;
	
	private final static int READ_TIMEOUT_POST = 20000;
	private final static int CONNECTION_TIMEOUT_POST = 20000;
	
    private static HttpEngine instance = null;

    private HttpEngine() {
    }

    public static HttpEngine getInstance() {
        if (instance == null) {
            instance = new HttpEngine();
        }
        return instance;
    }
	

    /**
     * 执行http请求
     * @param httpType
     * @param url
     * @param paramsList
     * @return
     * @throws Exception
     */
    public String execute(HttpType httpType, String url, List<Parameter> paramsList) throws IOException, NullParameterException {
		HttpURLConnection httpURLConnection = null;
    	String response = null;
		checkUrlNull(url);

		if (httpType == HttpType.GET) {
			if (!isParamNull(paramsList)) {
//				url += "?" + buildParamsString(paramsList);
				url += buildParamsString(paramsList);
			}
			KLog.i("url = " + url);
			URL realUrl = new URL(url);
			httpURLConnection = (HttpURLConnection) realUrl.openConnection();

			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setConnectTimeout(CONNECTION_TIMEOUT_GET);
			httpURLConnection.setReadTimeout(READ_TIMEOUT_GET);

			//response = httpGet(url, paramsList);
		}else if (httpType == HttpType.POST) {
			KLog.i("url = " + url);
			URL realUrl = new URL(url);
			httpURLConnection = (HttpURLConnection) realUrl.openConnection();

			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setConnectTimeout(CONNECTION_TIMEOUT_POST);
			httpURLConnection.setReadTimeout(READ_TIMEOUT_POST);

			//response = httpPost(url, paramsList);
		}


		httpURLConnection.setDoInput(true);
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
		//设置请求体的类型是文本类型
		httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//		//设置请求体的长度
//		httpURLConnection.setRequestProperty("Content-Length", String.valueOf(url.length()));

		//所有的配置必须在connect之前
		httpURLConnection.connect();


		if(httpType == HttpType.POST){
			//write data
			String request = buildParamsString(paramsList);
			DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
			dataOutputStream.writeBytes(request);
			dataOutputStream.flush();
			dataOutputStream.close();
		}

		int statusCode = httpURLConnection.getResponseCode();
		KLog.i("statusCode = "+statusCode);
		if(statusCode == HttpURLConnection.HTTP_OK){
			//read data
			InputStream inputStream = httpURLConnection.getInputStream();
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			int len = 0;
			byte[] buffer = new byte[1024];
			while((len = inputStream.read(buffer)) != -1){
				outputStream.write(buffer, 0, len);
			}
			response = new String(outputStream.toString());
			KLog.i( "response = "+response);
			inputStream.close();
			outputStream.close();
		}
		httpURLConnection.disconnect();
    	return response;
	}


	

	private void checkUrlNull(String url) throws NullParameterException {
		if (TextUtils.isEmpty(url)) {
			throw new NullParameterException("url is null !");
		}
	}
	
	private boolean isParamNull(List<Parameter> paramsList) {
		boolean isParamNull = false;
		if (paramsList == null || paramsList.size() == 0) {
			isParamNull = true;
		}
		return isParamNull;
	}
	
	
    /**
     * 拼接参数集
     * @param paramsList
     * @return
     */
    private String buildParamsString(List<Parameter> paramsList) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Parameter parameter : paramsList) {
        	stringBuilder.append("&");
        	stringBuilder.append(parameter.getKey());
            stringBuilder.append("=");
            try {
                stringBuilder.append(URLEncoder.encode(parameter.getValue(), ENCODE_TYPE));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
		}
        String paramsString = stringBuilder.substring(0, stringBuilder.length());
        KLog.i("paramsString = "+paramsString);
        return paramsString;
    }
	
	
//	/**
//	 * 把Parameter类型集合转换成NameValuePair类型集合
//	 * @param params 参数集合
//	 * @return
//	 */
//	private List<BasicNameValuePair> buildNameValuePair(List<Parameter> params) {
//		List<BasicNameValuePair> result = new ArrayList<BasicNameValuePair>();
//		for (Parameter param : params) {
//			BasicNameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
//			result.add(pair);
//		}
////		Log.i(TAG, "BasicNameValuePairList = "+result.toString());
//		return result;
//	}
}
